import win32process
import win32api
import win32con
import ctypes


def read_memory_data(pid, address):
    value = ctypes.c_uint32()

    # 要读取的地址,用 c_void_p 显式转换
    address_c = ctypes.c_void_p(address)

    # 打开目标进程,并获取原始句柄
    process_handle = win32api.OpenProcess(win32con.PROCESS_ALL_ACCESS, False, pid)
    raw_handle = process_handle.handle  # 获取原始整数句柄

    # 获取模块基址（可选）
    base_address = win32process.EnumProcessModules(process_handle)[0]

    # 使用 raw_handle 和 address_c
    success = ctypes.windll.kernel32.ReadProcessMemory(
        raw_handle, address_c, ctypes.byref(value), ctypes.sizeof(value), None
    )

    if success:
        print("Read successfully=", value.value, "\n")
        return value.value
    else:
        error_code = ctypes.windll.kernel32.GetLastError()
        print("Reading failed,Error code=", error_code, "\n")
        return None


# 进程的唯一标识符
pid = 1234
# 数据的内存地址
address = 0x0000001H
read_memory_data(pid, address)
